package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    RedissonClient redissonClient;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    private IVoucherOrderService proxy;
    private String queueName = "stream.orders";

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("lua/seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private static ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct  // 构建完成之后调用，由Spring提供
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
        // 在主线程初始化代理对象

    }

    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            log.info("【订单处理线程开始执行!】{}", Thread.currentThread().getId());
            while (true) {
                try {
                    // 获取消息队列中的订单
                    List<MapRecord<String, Object, Object>> read = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    // 判断消息是否获取成功
                    if (read==null || read.isEmpty()) {
                        continue;
                    }
                    // 解析消息
                    MapRecord<String, Object, Object> record = read.get(0);// 消息id-key-value
                    RecordId id = record.getId();
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

                    // 如果获取成功，下单
                    handleVoucherOrder(voucherOrder);
                    // ACK确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1", id);

                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    handlePengingList();
                }
            }
        }
    }

    private void handlePengingList() {
        while (true) {
            try {
                // 获取消息队列中的订单
                List<MapRecord<String, Object, Object>> read = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),     // 读取penging不用阻塞
                        StreamOffset.create(queueName, ReadOffset.from("0"))
                );
                // 判断消息是否获取成功
                if (read==null || read.isEmpty()) {
                    // 没有异常消息
                    break;
                }
                // 解析消息
                MapRecord<String, Object, Object> record = read.get(0);// 消息id-key-value
                RecordId id = record.getId();
                Map<Object, Object> value = record.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

                // 如果获取成功，下单
                handleVoucherOrder(voucherOrder);
                // ACK确认
                stringRedisTemplate.opsForStream().acknowledge(queueName,"g1", id);

            } catch (Exception e) {
                log.error("处理pendingList", e);
            }
        }
    }


    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        log.info("【处理订单!】{}-{}", Thread.currentThread().getId(), voucherOrder.toString());
        // 子线程调用, 不能够通过UserHolder来获取用户id了
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();

        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean isLock = lock.tryLock();
        if (!isLock) {
            log.error("不允许重复下单");
        }
        // 子线程也无法获取代理类,  可以通过主线程获取后赋值给类的成员变量
        try {
            proxy.createVoucher(voucherOrder);
        } finally {
            lock.unlock();
        }

    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorker.nextId("order");
        // 执行lua脚本
        int execute = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId)
        ).intValue();

        log.info("下单！");

        if (execute != 0) {
            // 不能购买
            return Result.fail(execute==1 ? "库存不足" : "不能重复下单");
        }

        // 获取代理对象, 在init函数中会报错
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        return Result.ok(orderId);
    }

    @Transactional
    // 事务方法必须是public, 不能加final修饰
    public void createVoucher(VoucherOrder order) {
        Long userId = order.getUserId();
        // 查询订单
        Integer count = query().eq("user_id", userId).eq("voucher_id", order.getVoucherId()).count();
        if (count > 0) {
            log.error("用户只能购买一次");
            return;
        }

        boolean success = seckillVoucherService.update().setSql("stock = stock-1").eq("voucher_id", order.getVoucherId()).gt("stock", 0).update();
        if (!success) {
            log.error("库存不足");
            return;
        }

        save(order);
    }
}
